package com.sba.server;

import de.codecentric.boot.admin.event.ClientApplicationEvent;
import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent;
import de.codecentric.boot.admin.notify.Notifier;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义消息通知类通过post请求通知服务状态
 * Created by 袁恩光 on 2018/1/25.
 */
//@Component
public class DDNotifier implements Notifier {

    @Override
    public void notify(ClientApplicationEvent event) {
        if (event instanceof ClientApplicationStatusChangedEvent) {
            ClientApplicationStatusChangedEvent statusChangedEvent = (ClientApplicationStatusChangedEvent) event;
            String serviceId = statusChangedEvent.getApplication().getName();
            String status;
            String url = statusChangedEvent.getApplication().getServiceUrl();
            Map<String, Object> map = new HashMap<>();
            map.put("serviceId", serviceId);
            map.put("url", url);
            if (statusChangedEvent.getFrom().getStatus().equalsIgnoreCase("UNKNOWN")) {
                status = "服务注册成功";
            } else {
                status = "服务已下线";
            }
            map.put("status", status);
            if (null == url || null == serviceId) {
                return;
            }
            MultiValueMap<String, Object> postData = new LinkedMultiValueMap<>();
            postData.setAll(map);
            HttpEntity entity = new HttpEntity<>(postData);
            new RestTemplate().postForObject("", entity, String.class);
        }
    }
}
